// Web Worker for data aggregation processing
import { GetPointInterpolated, Point } from '../tools/aggregateMath';

// 定义消息类型
interface WorkerMessage {
  type: 'process';
  data: Array<[string, number, number]>; // [deviceNo, xValue, yValue]
  aggregateMode: number; // 聚合模式: 1=平均, 2=累加, 其他=最大值
  numberOfPoints: number; // 点数
  showMode: number;
  isYSum: boolean;
}

interface WorkerResponse {
  type: 'result';
  data: {
    computeResult: Array<{
      sn: string;
      xys: Array<[number, number]>;
      ymax: number;
      ymin: number;
    }>;
    max: number;
    min: number;
    xMin: number;
    xMax: number;
  };
}

// 监听主线程消息
self.onmessage = function(e: MessageEvent<WorkerMessage>) {
  if (e.data.type === 'process') {
    const { data, aggregateMode, numberOfPoints, showMode, isYSum } = e.data;

    try {
      // 转换数据格式为Point数组
      const points: Point[] = data.map(item => ({
        x: item[1], // xValue
        y: item[2], // yValue
        sn: item[0]  // deviceNo
      }));

      // 调用统计方法
      const result = GetPointInterpolated(points, numberOfPoints, aggregateMode, showMode, isYSum);

      // 发送结果回主线程
      const response: WorkerResponse = {
        type: 'result',
        data: result
      };

      self.postMessage(response);
    } catch (error) {
      console.error('Error in worker:', error);
      self.postMessage({
        type: 'error',
        error: error instanceof Error ? error.message : 'Unknown error'
      });
    }
  }
};
